<template>
  <div id="preRepair" class="preRepair">
    <!-- header -->
    <magic-header :titleName="fromShop ? '预约服务' : (appointmentType == 'protect' ? '预约保养' : '预约维修')" :returnNative="$route.params.native"></magic-header>
    <cells>
      <cell v-if="unReceivedCoupons && unReceivedCoupons.length > 0" label="有优惠券可领取" v-tap="{ methods: goCoupon }"></cell>
      <cell label="服务项目" :value="services | getServiceName" v-tap="{ methods: goSelectService }"></cell>
      <cell label="预估服务费用" :value="estimatePrice" v-tap="{methods: goEstimatePrice}"></cell>
      <!-- 车辆信息 @TODO 选择车辆,添加车辆 -->
      <div class="pre-drive-car" layout="row" layout-align="space-between center" v-tap="{methods: goSelectCar}">
        <div layout="row" layout-align="space-between center">
          <!-- image -->
          <div>
            <img :src="addPath(car.brandLogo)" v-if="car && car.brandLogo">
            <img :src="defaultCarImg" v-else>
          </div>

          <!-- detail -->
          <div class="txt">
            <h2>{{car ? (car.brand || car.type ? car.brand+' '+car.type : '') : '选择车型'}}</h2>
          </div>
        </div>
        <!-- >箭头 -->
        <div class="link" style=" line-height: 50px;">
          <img :src="more" class="mu-icon material-icons more-img">
        </div>
      </div>
      <!-- </cells>
    <cells> -->
      <cell label="姓名" :value="info.name" v-tap="{ methods: editInfo, inputType: 1 }"></cell>
      <cell label="称谓" :value="info.gender | genderFilter" v-tap="{methods: editInfo, inputType: 2 }"></cell>
      <cell label="手机号" :value="info.mobile" v-tap="{methods: editInfo, inputType: 3 }"></cell>
      <cell label="到店时间" :value="dateTime" v-tap="{methods: showDateTime}"></cell>
      <cell v-if="appointmentType == 'protect'" label="行驶路程(km)" :value="info.drivingRange" v-tap="{methods: editInfo, inputType: 5 }"></cell>
      <cell label="车牌号" :value="info.plateNumber" v-tap="{methods: editInfo, inputType: 4 }"></cell>
    </cells>

    <!-- button -->
    <div layout="row" layout-align="center center" style="margin: 20px 0;">
      <mu-flat-button label="立即预约" backgroundColor="#FB8713" color="#FFF" v-tap="{methods: createAppointment}" />
    </div>

    <!-- 隐藏, 供弹出展示 -->
    <!-- 时间选择 -->
    <date-time :isShow="dateTimeShow" @closeDateTime="dateTimeShow=false" @getDateTime="getDateTime"></date-time>

    <!-- 信息编辑 -->
    <icar-dialog :isShow="dialogShow" @dialogClose="dialogClose" class="info-edit">
      <div class="info-content">
        <!-- text -->
        <mu-text-field :label="title" :hintText="placeholder" v-model="value" v-if="type == 1" :fullWidth="true" underlineFocusClass="info-edit-input" />
        <!-- radio -->
        <div layout="row" layout-align="space-around center" v-if="type == 2">
          <!-- <mu-radio label="先生" name="group" nativeValue="0" v-model="value" iconClass="info-edit-checked"   />
          <mu-radio label="女士" name="group" nativeValue="1" v-model="value" iconClass="info-edit-checked"   /> -->
          <icar-radio label="先生" nativeValue="0" v-model="value"></icar-radio>
          <icar-radio label="女士" nativeValue="1" v-model="value"></icar-radio>
        </div>
      </div>
      <!-- button -->
      <div layout="row" layout-align="center center" class="full-button">
        <mu-flat-button label="确定" backgroundColor="#FB8713" color="#FFF" v-tap="{methods: getValue}" />
      </div>
    </icar-dialog>
    <icar-dialog :isShow="tipShow" @dialogClose="tipClose" class="cancel-appoint">
      <div slot="head" class="header-cancel-appoint-item">友情提示</div>
      <div class="list-cancel-appoint-item">
        <div>您上次预约存在取消项目:</div>
        <ul>
          <li v-for="(item, index) in canceledAppointItems" :key="index">{{item.name}}</li>
        </ul>
      </div>
      <div style="text-align:center;">
        <mu-flat-button label="确定" backgroundColor="#FB8713" color="#FFF" v-tap="{methods: tipClose}" />
      </div>
    </icar-dialog>
  </div>
</template>

<script>
// obj
import wx from "weixin-js-sdk";
// components
import cells from "components/cells";
import cell from "components/cell";
import dateTime from "components/dateTimePicker/dateTimePicker";
import icarDialog from "components/dialog/dialog";
import icarRadio from "components/radio/radio";
import icarCheckbox from "components/checkbox/checkbox";
import magicHeader from "components/magicHeader";
// image
import defaultImg from "assets/APP-icon_80.png";
import defaultCarImg from "assets/default_user_icon.png";
import more from "assets/more.svg";
// services
import {
  ListCancelledAppointmentItem,
  QueryCarInfoList,
  QueryRepairAppointment,
  QueryMaintainAppointment,
  FillInOrder,
  CreateOrder,
  CalculateOrder,
  getEstimatePrice
} from "services/appointment/appoint";
// vuex
import appointStore from "services/appointment/appoint";

export default {
  components: {
    cells,
    cell,
    dateTime,
    icarDialog,
    icarRadio,
    icarCheckbox,
    magicHeader
  },
  data() {
    return {
      fromShop: false,
      defaultImg,
      defaultCarImg,
      more,
      appointmentType: "", // 预约类型 repair protect
      ownCars: [], // 用户绑定的车辆
      car: null, // 车辆相关信息
      info: {}, // 个人相关信息 姓名 性别 手机号码等
      services: appointStore.getters.getServices, // 服务项目
      orderType: "", // 订单类型 3-维修 4-保养
      couponCodes: [], // 可用优惠券信息
      couponIndex: 0, // 选择的优惠券
      unReceivedCoupons: [], // 未领取的优惠券信息
      estimatePrice: "", // 预估服务费用
      paymentMethods: [], // 支付方式
      canceledAppointItems: [], // 上次取消的预约项目
      amount: 0, // 总价
      // components view-model
      tipShow: false,
      couponShow: false,
      dateTimeShow: false, // timepicker 展示
      dialogShow: false,
      // 信息编辑相关
      dateTime: "", // 时间 timepicker
      title: "", // label type为1时有效1
      value: "", // 信息编辑 值
      type: "1", // 编辑界面的input类型 1-text 2-radio
      placeholder: "", // 提示信息
      inputType: "" // 编辑哪个数据 1-姓名 2-性别 3-手机号 4-车牌号 5-里程 10-服务项目 11-服务费用
    };
  },
  watch: {
    // services(){
    //   // 首次进入查询优惠信息
    //   this.fillInOrder()
    // }
  },
  methods: {
    // Init method
    init() {
      let vm = this;
      vm.fromShop = this.$route.query.fromShop;
      // 列出上次取消的预约项目
      this.listCancelledAppointmentItem();
      // 查询车辆信息
      this.queryCarInfoList().then(function () {
        // 查询基本信息
        vm.appointmentType = vm.$route.params.is;
        switch (vm.appointmentType) {
          case "repair":
            vm.orderType = 3;
            queryRepair(vm);
            break;
          case "protect":
            vm.orderType = 4;
            queryMaintain(vm);
            break;
        }
        // 首次进入查询优惠信息
        vm.fillInOrder();
      });
    },
    // 列出上次取消的预约项目
    listCancelledAppointmentItem() {
      ListCancelledAppointmentItem.bind(this)(
        {},
        resp => {
          if (resp.items.length > 0) {
            this.canceledAppointItems = resp.items;
            this.tipShow = true;
          }
        },
        (err, code) => {
          //// test data
          // this.canceledAppointItems = [
          //   { name: "项目1" },
          //   { name: "项目2" },
          //   { name: "项目3" },
          //   { name: "项目4" },
          //   { name: "项目5" }
          // ];
          // this.tipShow = true;
          ////
          this.$.toast(err);
        }
      );
    },
    // 获取注册的车辆信息
    queryCarInfoList() {
      let vm = this;
      return new Promise(function (resolve, reject) {
        QueryCarInfoList.bind(vm)(
          {
            userId: vm.user.userId,
            carId: vm.user.carId
          },
          resp => {
            vm.ownCars = resp.ownCars;
            vm.ownCars.forEach(function (carInfo) {
              // 默认绑定的第一辆车为准
              if (carInfo.defaultCar == "1") {
                vm.setCar(carInfo);
                vm.user.carId = carInfo.id;
              }
            });
            resolve();
          }
        );
      });
    },
    // set appoint car
    setCar(carInfo) {
      this.car = carInfo;
      this.info.plateNumber = carInfo.plateNumber;
      this.info.drivingRange = carInfo.drivingRange;
      // this.car.type = carInfo.type;
      // this.car.brand = carInfo.brand;
      // this.car.brandLogo = carInfo.brandLogo;
    },
    // 领取优惠券
    goCoupon() {
      this.$router.push({
        name: "coupon_native"
      });
    },
    // 选择服务项目
    goSelectService() {
      //sg_goodsList?routeSource=serviceSelect&typeId=2
      this.$router.push({
        name: "sg_goodsList",
        query: {
          routeSource: "serviceSelect",
          typeId: 2
        }
      });
    },
    // 预估服务费用详情
    goEstimatePrice() {
      if (this.services && this.services.cartItems.length > 0) {
        this.$router.push({
          name: "estimate_native"
        });
      } else {
        this.$.toast("请先选择服务项目");
      }
    },
    // 选车
    goSelectCar() {
      this.$.push("router_selectCar", {}, resp => {
        alert(resp);
        resp = JSON.parse(resp);
        let id = resp.id;
        let plateNumber = resp.plateNumber;
        let headUrl = resp.headUrl;
        let brand = resp.brand;
        let series = resp.series;
        let type = resp.type;
        let drivingRange = resp.drivingRange;
        this.setCar(
          Object.assign(
            {},
            {
              brandLogo: headUrl,
              drivingRange: drivingRange
            },
            {
              id,
              plateNumber,
              headUrl,
              brand,
              series,
              type,
              drivingRange
            }
          )
        );
      });
    },
    /**
     * 填写订单,获取优惠券信息, 准确计算服务费用
     * @param orderType 3:预约维修,4:预约保养
     */
    fillInOrder() {
      if (
        this.services &&
        this.services.cartItems &&
        this.services.cartItems.length > 0
      ) {
        FillInOrder.bind(this)(this.getFillInOrderRequest(), resp => {
          console.log(resp);
          // 可用的优惠券, 计算预估服务费用
          this.couponCodes = resp.couponCodes;
          appointStore.commit("setCouponCodes", this.couponCodes);
          // @TODO unreceived coupon 字面意思未领取的优惠券, 实际返回的是领取的优惠券
          this.unReceivedCoupons = resp.unReceivedCoupons;
          appointStore.commit("setUnReceivedCoupons", this.unReceivedCoupons);
          // 支付方式
          this.paymentMethods = resp.paymentMethods;

          // CalculateOrder 计算订单价格（获取促销优惠价格 运费等）
          this.calculateOrder()
        });
      }
    },
    getFillInOrderRequest() {
      this.services.cartItems.forEach(cartItem => {
        cartItem.product = Object.assign({}, cartItem.product, {
          couponPromotions: [],
          reviews: [],
          notice: ""
        });
      });
      return {
        orderType: this.orderType,
        cartItems: this.services.cartItems
      };
    },
    // 计算订单价格
    calculateOrder() {
      CalculateOrder.bind(this)(this.getCalculateReq(), resp => {
        // 实际支付的价格
        this.estimatePrice = resp.amountPaid < 0 ? 0 : resp.amountPaid;
        this.amount = resp.amount
      })
    },
    // type 0-商家优惠 1-优惠券
    getCalculateReq(type) {
      let couponIndex = appointStore.getters.getCouponIndex
      let req = {
        "cartItems": this.services.cartItems,
        "couponIds": this.couponCodes && this.couponCodes.length > 0 && couponIndex > -1 ? [this.couponCodes[couponIndex].coupon.id] : null,
      }
      return req;
    },
    // 展示时间组件
    showDateTime() {
      this.dateTimeShow = !this.dateTimeShow;
    },
    // 获取时间
    getDateTime(time) {
      this.dateTime = time.join("");
    },
    // 编辑个人信息
    editInfo(params) {
      // inputType 1-姓名 2-性别 3-手机号 4-车牌号 5-行驶路程
      this.inputType = params.inputType;
      if (params.inputType == 1) {
        this.value = this.info.name;
        this.type = "1";
        this.placeholder = "请输入姓名";
      } else if (params.inputType == 2) {
        this.value = this.info.gender;
        this.type = "2";
        this.placeholder = "请选择";
      } else if (params.inputType == 3) {
        this.value = this.info.mobile;
        this.type = "1";
        this.placeholder = "请输入手机号";
      } else if (params.inputType == 4) {
        this.value = this.info.plateNumber;
        this.type = "1";
        this.placeholder = "请输入车牌号";
      } else if (params.inputType == 5) {
        this.value = this.info.drivingRange;
        this.type = "1";
        this.placeholder = "请输入里程数";
      }
      this.dialogShow = true;
    },
    // 获取个人信息 inputType 1-姓名 2-性别 3-手机号 4-车牌号 5-行驶路程
    getValue(value) {
      if (this.inputType == 1) {
        this.info.name = this.value;
        this.info.gender = this.info.gender ? this.info.gender : 0;
      } else if (this.inputType == 2) {
        this.info.gender = this.value;
      } else if (this.inputType == 3) {
        this.info.mobile = this.value;
      } else if (this.inputType == 4) {
        this.info.plateNumber = this.value;
      } else if (this.inputType == 5) {
        this.info.drivingRange = this.value;
      }
      this.dialogClose();
    },
    // dialog关闭事件
    dialogClose() {
      this.dialogShow = false;
    },
    tipClose() {
      this.tipShow = false;
    },
    // 预约
    createAppointment() {
      // 信息校验
      if (checkAppointmentParams(this, this.orderType)) {
        let request = this.getCreateOrderReq();
        CreateOrder.bind(this)(
          request,
          resp => {
            console.log(resp);
            let orderId = resp.id;
            this.$router.replace({
              name: "orderDetail",
              params: {
                orderId: orderId
              }
            });
            // @TODO 调转到订单页面
          },
          (err, code) => {
            this.$.toast(err);
          }
        );
        console.log(request);
      }
    },
    // 获取createOrder request
    getCreateOrderReq() {
      // payment id
      let paymentMethod = this.paymentMethods.filter(paymentMethod => {
        return paymentMethod.method == 2;
      });
      let paymentMethodId = paymentMethod[0].id;

      // coupon id
      let couponIndex = appointStore.getters.getCouponIndex
      let couponCode = this.couponCodes[couponIndex];
      let couponCodeId = couponCode ? couponCode.id : null;

      // cartItems
      let cartItems = this.getCartItems();
      let appointment = this.getAppointment();
      let request = {
        amount: String(Number(this.amount)),
        amountPaid: this.estimatePrice,
        orderType: String(this.orderType),
        cartItems: cartItems,
        paymentMethodId: paymentMethodId,
        shippingMethodId: null,
        // couponCodeId: this.couponCodes && this.couponCodes.length > 0 && couponIndex > -1 ? this.couponCodes[couponIndex].id : null,
        couponIds: this.couponCodes && this.couponCodes.length > 0 && couponIndex > -1 ? [this.couponCodes[couponIndex].coupon.id] : null,
        appointment: appointment
      };

      return request;
    },
    getCartItems() {
      let _cartItems = []
      let cartItems = Object.assign([], this.services.cartItems || []);
      cartItems.forEach(cartItem => {
        _cartItems.push({
          "amount": String(Number(cartItem.product.price)),
          "quantity": "1",
          "product": {
            "id": cartItem.product.id,
            "price": cartItem.product.price,
          }
        })
      })

      return _cartItems
    },
    // 获取预约信息
    getAppointment() {
      let appointment = {
        name: this.info.name,
        gender: this.info.gender,
        mobile: this.info.mobile,
        plateNumber: this.info.plateNumber,
        repairItemIds: this.orderType == 3 ? this.getRepairItemIds() : null,
        shopId: this.$.shopId,
        userId: this.$.userId,
        carId: this.car.id, // 个人车辆
        // productId: "" 选择车辆 // 商品车辆
        appontmentDate: this.dateTime,
        drivingRange: this.orderType == 4 ? this.info.drivingRange : null
      };
      return appointment;
    },
    getRepairItemIds() {
      let repairItemIds = [];
      let cartItems = this.services.cartItems || [];
      cartItems.forEach(item => {
        repairItemIds.push(item.product.id);
      });
      return repairItemIds;
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.init();
    });
  },
  filters: {
    genderFilter(value) {
      return ["先生", "女士"][value];
    },
    getServiceName(items) {
      if (items && items.cartItems && items.cartItems.length > 0) {
        if (items.cartItems.length > 1) {
          return `${items.cartItems[0].product.name}等${
            items.cartItems.length
            }件`;
        } else {
          return `${items.cartItems[0].product.name}`;
        }
      } else {
        return "";
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.services = appointStore.getters.getServices;
      vm.fillInOrder();
    });
  }
};
// 信息校验
function checkAppointmentParams(vm, type) {
  let result;
  result =
    validService(
      vm,
      vm.services,
      vm.services && vm.services.cartItems && vm.services.cartItems.length > 0,
      "请选择服务项目"
    ) &&
    validService(
      vm,
      vm.car,
      vm.car ? true : false,
      `你还没有选择要${vm.orderType == 3 ? "维修" : "保养"}的车辆`
    ) &&
    validService(vm, vm.info.name, /^(\w|[^x00-xff])+$/, "请输入姓名") &&
    validService(vm, vm.info.gender, /^(0|1)$/, "请选择称谓") &&
    validService(vm, vm.info.mobile, /^1(\d){10}$/, "请输入11位手机号码") &&
    validService(
      vm,
      vm.dateTime,
      vm.dateTime ? vm.dateTime.length > 0 : false,
      "请输入到店时间"
    ) &&
    validService(
      vm,
      vm.dateTime,
      timevalidService(vm.dateTime),
      "预约时间不能早于当前时间",
      "time"
    ) &&
    (type == "4"
      ? validService(vm, vm.info.drivingRange, /^[1-9]\d*$/, "请输入行驶路程")
      : true) &&
    validService(
      vm,
      vm.info.plateNumber,
      /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/,
      "请输入车牌号"
    );
  return result;
}

/**
 * 信息校验工具函数
 * @augments vm view-model
 * @augments val 校验的值
 * @augments cond 正则 或 Boolean
 * @augments msg 提示信息
 * @augments type 'time': 表示时间校验, 不用正则
 */
function validService(vm, val, cond, msg, type) {
  let result;
  if (String(val)) {
    result = cond instanceof RegExp ? cond.test(val) : cond;
  } else {
    result = false;
  }
  if (!result) {
    vm.$.toast(msg);
  }
  return result;
}

// 与当前时间进行校验
function timevalidService(date) {
  var cdata = new Date();
  var _data = new Date(date.split(" ").join("T"));
  return _data.getTime() > cdata.getTime();
}

//获取车辆维修界面信息
function queryRepair(vm) {
  QueryRepairAppointment.bind(vm)(
    {
      productId: (vm.car && vm.car.id) ? "" : vm.user.carId
    },
    resp => {
      vm.info = resp.repairAppointment;
      vm.info.plateNumber = vm.info.plateNumber
        ? vm.info.plateNumber
        : vm.car.plateNumber;
    }
  );
}

// 获取车辆保养界面信息
function queryMaintain(vm) {
  QueryMaintainAppointment.bind(vm)(
    {
      productId: vm.car && vm.car.id,
      // userId: vm.user.userId,
      carId: (vm.car && vm.car.id) ? "" : vm.user.carId
    },
    resp => {
      vm.info = resp.maintanceAppointment;
      vm.info.plateNumber = vm.info.plateNumber
        ? vm.info.plateNumber
        : vm.car.plateNumber;
    }
  );
}
</script>

<style lang="scss" scoped>
.pre-drive-car {
  height: auto !important;
  padding: 10px;
  border-bottom: 1px solid #eeeeee;
  img {
    width: 100px;
  }
}
.txt {
  h2 {
    display: inline-block;
    width: 100%;
    float: left;
    font-size: 14px;
    white-space: normal;
    position: relative;
    left: 5px;
    vertical-align: middle;
    font-weight: initial;
  }
  h3 {
    float: left;
    position: relative;
    left: 5px;
    font-size: 14px;
    color: red;
    vertical-align: middle;
    span {
      color: black;
    }
  }
}
.full-button {
  button {
    width: 100%;
  }
}
.info-content {
  padding-bottom: 25px;
}
.item.repair {
  padding: 20px;
  font-size: 15px;
  border-bottom: 1px solid #cbcbcb;
  display: flex;
  align-items: center;
}
.pre-repair-cell {
  padding-right: 10px;
  min-height: 45px;
  border-bottom: 1px solid #eeeeee;
  .label {
    padding-left: 14px;
    color: #0c0c0c;
    font-size: 1.1rem;
  }
  .content {
    font-size: 12px;
    color: #6c6c6c;
    max-width: 70%;
    padding-right: 0;
  }
  > div {
    flex: 1 1 90%;
    max-width: 90%;
    max-height: 100%;
    box-sizing: border-box;
  }
}
.more-img {
  width: 15px !important;
  height: 15px;
  margin-left: 10px;
  margin-right: 5px;
}
.cancel-appoint {
  font-size: 15px;
  .header-cancel-appoint-item {
    padding: 5px;
    padding-left: 0;
  }
  .list-cancel-appoint-item {
    padding-bottom: 10px;
    li {
      line-height: 20px;
    }
  }
}
</style>
<style lang="scss">
.info-edit-checked {
  &.mu-radio-icon-checked,
  &.mu-checkbox-icon-checked {
    color: #f98700;
  }
  &.mu-radio-icon-uncheck,
  &.mu-checkbox-icon-uncheck {
    color: #939393 !important;
  }
}
.info-edit-input {
  background-color: #f98700;
}
.mu-flat-button {
  min-width: 50%;
}
.repair-label {
  padding-left: 20px;
}
</style>

